package models

import (
	"errors"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"github.com/pborman/uuid"
	"time"
)

func init() {

}

type ClientDetails struct {
	Id           int64     `json:"id"`
	PackageName  string    `orm:"index" json:"packageName"`
	ResponseType string    `form:"response_type"` //code token
	ClientId     string    `form:"client_id" json:"clientId"`
	ClientSecret string    `form:"client_secret" json:"clientSecret"`
	RedirectUri  string    `form:"redirect_uri" json:"redirectUri"`
	Scope        string    `form:"scope" json:"scope"`
	State        uint32    `form:"state" json:"state"`
	CreateTime   time.Time `json:"createTime"`
}

type ClientToken struct {
	UserId       string    `json:"-" form:"user_id" orm:"pk"`
	AccessToken  string    `json:"accessToken"  form:"access_token" orm:"index"` //code token
	TokenType    string    `json:"tokenType" form:"token_type"`
	RefreshToken string    `json:"refreshToken" form:"refresh_token"`
	ExpiresIn    int32     `json:"expiresIn" form:"expires_in"`
	Scope        string    `json:"scope" form:"scope"`
	CreateTime   time.Time `json:"-"`
	TokenTime    time.Time `json:"-"`
}

// 网页生成clientid和clientSecret
func MakeClientDetails(packageName string) (clientDetails ClientDetails, err error) {
	o := orm.NewOrm()
	clientDetails.PackageName = packageName
	clientDetails.ClientId = uuid.New()
	clientDetails.ClientSecret = uuid.New()
	clientDetails.CreateTime = time.Now()
	clientDetails.ResponseType = "code"
	clientDetails.Scope = "user,msg,pay"
	clientDetails.State = 0
	id, err := o.Insert(&clientDetails)
	if id < 0 {
		err = errors.New("error  db")
	}
	return
}

func ValidClientDetails(clientId string, clientSecret string) error {
	o := orm.NewOrm()
	clientDetails := ClientDetails{ClientId: clientId}
	err := o.Read(&clientDetails, "ClientId")
	if err != nil {
		return err
	}
	return nil
}

func Token(accessToken string) (clientToken ClientToken, err error) {
	valid := validation.Validation{}

	if v := valid.Required(accessToken, "access_token"); !v.Ok {
		err = errors.New(v.Error.Key + " " + v.Error.Message)
		return
	}

	o := orm.NewOrm()
	//查询授权信息
	clientToken = ClientToken{AccessToken: accessToken}
	err = o.Read(&clientToken, "AccessToken")
	if err != nil {
		return
	}
	if clientToken.TokenTime.Add(time.Duration(clientToken.ExpiresIn) * time.Second).Before(time.Now()) {
		err = errors.New("Authorize expire")
	}
	return
}
